package freespiritsocial.io.user.viewmodel

import freespiritsocial.io.user.R
import freespiritsocial.io.user.base.App
import freespiritsocial.io.user.network.apiService
import freespiritsocial.io.user.network.upload.IUploadApi
import freespiritsocial.io.user.network.upload.UploadDelegate
import me.hgj.jetpackmvvm.base.viewmodel.BaseViewModel
import me.hgj.jetpackmvvm.callback.databind.BooleanObservableField
import me.hgj.jetpackmvvm.callback.databind.IntObservableField
import me.hgj.jetpackmvvm.callback.databind.StringObservableField
import me.hgj.jetpackmvvm.ext.request
import me.hgj.jetpackmvvm.ext.requestNoCheck
import me.hgj.jetpackmvvm.network.AppException
import me.hgj.jetpackmvvm.util.MD5Utils
import java.io.File

class SignUpModel: BaseViewModel(),IUploadApi by UploadDelegate() {
    val isThirdSignUp = BooleanObservableField(false)
    val thirdPartyId = StringObservableField("")
    val thirdPartyType = IntObservableField(0)
    val phoneNumber = StringObservableField()
    val countryCode = StringObservableField("+44")
    val password = StringObservableField()
    val code = StringObservableField()

    //=========用户信息=========
    val name = StringObservableField()
    val username = StringObservableField()
    val email = StringObservableField()
    val gender = IntObservableField(-1)
    val dob = StringObservableField()
    val country = StringObservableField("Britain")
    val userAvatar = StringObservableField("")

    val countDownTip = StringObservableField(App.instance.getString(R.string.code_get))

    fun setGender(gender: Int) {
        this.gender.set(gender)
    }

    fun checkMobile(success: () -> Unit) {
        request({
            apiService.checkMobile(countryCode.get(),phoneNumber.get().replace(" ",""))
        },{
            success.invoke()
        },isShowDialog = true)
    }

    fun checkSmsCode(success: () -> Unit) {
        request({
            apiService.checkSmsCode(
                hashMapOf<String,Any>(
                    "areaCode" to countryCode.get(),
                    "code" to code.get(),
                    "mobile" to phoneNumber.get().replace(" ",""),
                    "type" to 1,
                )
            )
        },{
            success.invoke()
        },isShowDialog = true)
    }

    fun sendSmsCode(type: Int = 1) {
        request({
            apiService.sendSmsCode(
                hashMapOf<String,Any>(
                    "areaCode" to countryCode.get(),
                    "mobile" to phoneNumber.get().replace(" ",""),
                    "type" to type,
                )
            )
        },{
        })
    }

    fun register(success: (String) -> Unit) {
        if (username.get().length < 6) {
            toast.postValue("User name must be at least 6 characters")
            return
        }
        requestNoCheck({
            val file = File(userAvatar.get())
            if (file.isFile) {
                val userAvatar = uploadFile(file)?.url ?: ""
                this.userAvatar.set(userAvatar)
            }
            if (isThirdSignUp.get()) {
                apiService.registerThird(
                    hashMapOf(
                        "birthday" to dob.get(),
                        "country" to country.get(),
                        "name" to name.get(),
                        "thirdPartyId" to thirdPartyId.get(),
                        "thirdPartyType" to thirdPartyType.get(),
                        "password" to MD5Utils.md5(password.get()),
                        "userAvatar" to userAvatar.get(),
                        "userEmail" to email.get(),
                        "userName" to username.get(),
                        "userSex" to gender.get()
                    )
                )
            } else {
                val register = apiService.register(
                    hashMapOf(
                        "areaCode" to countryCode.get(),
                        "birthday" to dob.get(),
                        "code" to code.get(),
                        "country" to country.get(),
                        "name" to name.get(),
                        "password" to MD5Utils.md5(password.get()),
                        "userAvatar" to userAvatar.get(),
                        "userEmail" to email.get(),
                        "userMobile" to phoneNumber.get().replace(" ",""),
                        "userName" to username.get(),
                        "userSex" to gender.get()
                    )
                )
                if (register.isSucces())
                    apiService.login(
                        hashMapOf(
                            "userMobile" to phoneNumber.get().replace(" ",""),
                            "areaCode" to countryCode.get(),
                            "password" to MD5Utils.md5(password.get())
                        )
                    )
                else
                    throw AppException(register.code,register.message)
            }
        },{ response ->
            response.body()?.let {
                if (it.isSucces()) {
                    response.headers()["token"]?.let(success)
                } else
                    toast.postValue(it.message)
            }
        },isShowDialog = true)

    }

    fun forget(success: (String) -> Unit) {
        val phoneNumber = phoneNumber.get().replace(" ","")
        requestNoCheck({
            val forgetPassword = apiService.forgetPassword(
                hashMapOf(
                    "areaCode" to countryCode.get(),
                    "code" to code.get(),
                    "mobile" to phoneNumber,
                    "password" to MD5Utils.md5(password.get())
                )
            )
            if (forgetPassword.isSucces())
                apiService.login(
                    hashMapOf(
                        "userMobile" to phoneNumber,
                        "areaCode" to countryCode.get(),
                        "password" to MD5Utils.md5(password.get())
                    )
                )
            else
                throw AppException(forgetPassword.code,forgetPassword.message)
        },{ response ->
            response.body()?.let {
                if (it.isSucces()) {
                    response.headers()["token"]?.let(success)
                } else
                    toast.postValue(it.message)
            }
        },isShowDialog = true)

    }

    fun faceBook(userId: String,loginFail: () -> Unit,loginSuccess: (String) -> Unit) {
        requestNoCheck({
            apiService.signInByThird(
                hashMapOf(
                    "thirdPartyId" to userId,
                    "thirdPartyType" to 3
                )
            )
        },{ response ->
            response.body()?.let {
                when {
                    it.isSucces() -> {
                        response.headers()["token"]?.let(loginSuccess)
                    }
                    it.code == 30000 -> {
                        loginFail()
                    }
                    else -> toast.postValue(it.message)
                }
            }
        },isShowDialog = true)
    }

    fun google(userId: String,loginFail: () -> Unit,loginSuccess: (String) -> Unit) {
        requestNoCheck({
            apiService.signInByThird(
                hashMapOf(
                    "thirdPartyId" to userId,
                    "thirdPartyType" to 2
                )
            )
        },{ response ->
            response.body()?.let {
                when {
                    it.isSucces() -> {
                        response.headers()["token"]?.let(loginSuccess)
                    }
                    it.code == 30000 -> {
                        loginFail()
                    }
                    else -> toast.postValue(it.message)
                }
            }
        },isShowDialog = true)
    }

}
